package com.sam.c_proxy;

import com.sam.service.IUserService;
import com.sam.service.impl.UserServiceImpl;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * cglib 代理
 */
public class UserServiceProxyFactory2 implements MethodInterceptor {

    public IUserService getUserServiceProxy() {

        Enhancer enhancer = new Enhancer();//帮我们生成代理对象

        enhancer.setSuperclass(UserServiceImpl.class);//设置被代理对象

        enhancer.setCallback(this);//设置代理要做什么

        IUserService userService = (IUserService) enhancer.create();

        return userService;
    }

    /**
     * @param proxyObj    被代理原始对象
     * @param method      被代理原始对象方法
     * @param args
     * @param methodProxy
     * @return
     * @throws Throwable
     */
    @Override
    public Object intercept(Object proxyObj, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
        //打开事务
        System.out.println("打开事务...");
        //调用原有方法
        Object object = methodProxy.invokeSuper(proxyObj, args);
        //提交事务
        System.out.println("提交事务...");
        return object;
    }
}
